package com.estock.platform.task;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.quartz.JobExecutionException;
import org.springframework.stereotype.Component;

import com.estock.common.model.Pair;
import com.estock.common.model.security.Stock;
import com.estock.common.util.CommonUtil;
import com.estock.common.util.StringUtil;
import com.estock.common.util.support.ESLogger;
import com.estock.common.util.support.StockPreCodeAndType;
import com.estock.platform.http.SinaStockBulkConn;
import com.estock.platform.http.response.SinaStockBulkResponse;
import com.estock.platform.manager.DBManager;
import com.estock.platform.task.support.ESJob;

/**
 * Suggest it to be executed on a weekly basis.
 * 
 * @author richard
 * 
 */
@Component
public class SilverBulletStockRegister extends ESJob {
	
	private static ESLogger logger = ESLogger
			.getLogger(SilverBulletStockRegister.class);
	
	private static final int BULK_SIZE = 20;
	List<Stock> bulkStocks = new ArrayList<Stock>(BULK_SIZE);


	@Override
	protected void executeJob() {
		logger.info("start executing job: RegisterStockByLoopJob at "
				+ new Date());

		List<Stock> dummyStocks = generateDummyStocks();
		int bulkSize = 0;
		int requestedNum = 0;
		int savedNum = 0;
		while (requestedNum < dummyStocks.size()) {
			while (bulkSize < BULK_SIZE && requestedNum < dummyStocks.size()) {
				bulkStocks.add(dummyStocks.get(requestedNum));
				bulkSize++;
				requestedNum++;
			}
			
			try {
				SinaStockBulkResponse response =  (SinaStockBulkResponse) new SinaStockBulkConn().request(bulkStocks, false);
				List<Stock> stocks = response.getStocks();
				for (Stock stock : stocks) {
					try {
						DBManager.getInstance().saveOrUpdate(stock);
						savedNum++;
					} catch (Exception e) {
						// continue
					}
				}
				
			} catch (Exception e) {
				// continue
			}
			
			bulkSize = 0;
			bulkStocks.clear();
		}
		
		logger.info("Try to request dummy %s stocks, saved %s stocks", requestedNum, savedNum);
	}

	public List<Stock> generateDummyStocks() {
		List<Pair> preCodeAndTypes = StockPreCodeAndType.getStockPrecodeAndType();
		List<Stock> stocks = new ArrayList<Stock>();
		for (Pair pair : preCodeAndTypes) {
			String preCode = String.valueOf(pair.getFirst());
			int stockType = Integer.valueOf(String.valueOf(pair.getSecond()));
			for (int i = 0; i <= 999; i++) {
				// padding left with 0 to 3 digits
				String suffixCode = StringUtil.padding(String.valueOf(i), "0",
						3);
				stocks.add(new Stock(preCode + suffixCode, "", stockType));
			}
		}
		return stocks;
	}

	public static void main(String[] args) throws JobExecutionException {
		CommonUtil.isUnitTest = true;
        
		new SilverBulletStockRegister().executeJob();
		
		CommonUtil.isUnitTest = false;
	}

}
